package com.starhub.system.database.controller;

import com.starhub.system.database.service.DatabaseUpgradeService;
import com.starhub.system.database.manager.SqlFileManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import com.starhub.system.database.config.DatabaseUpgradeConfig;

/**
 * 数据库升级控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/system/database")
public class DatabaseUpgradeController {
    
    @Autowired
    private DatabaseUpgradeService databaseUpgradeService;
    
    @Autowired
    private SqlFileManager sqlFileManager;
    
    @Autowired
    private ResourceLoader resourceLoader;
    
    @Autowired
    private DatabaseUpgradeConfig config;
    
    /**
     * 手动触发数据库升级
     */
    @PostMapping("/upgrade")
    public ResponseEntity<Map<String, Object>> manualUpgrade() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("手动触发数据库升级");
            databaseUpgradeService.executeUpgrade();
            
            result.put("success", true);
            result.put("message", "数据库升级执行完成");
            
        } catch (Exception e) {
            log.error("手动触发数据库升级失败: {}", e.getMessage(), e);
            
            result.put("success", false);
            result.put("message", "数据库升级执行失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 测试文件扫描功能
     */
    @GetMapping("/test-scan")
    public ResponseEntity<Map<String, Object>> testFileScan(@RequestParam(defaultValue = "mysql") String databaseType) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("测试文件扫描功能，数据库类型: {}", databaseType);
            
            // 测试文件扫描
            List<File> sqlFiles = sqlFileManager.getSqlFiles(databaseType);
            
            result.put("success", true);
            result.put("databaseType", databaseType);
            result.put("fileCount", sqlFiles.size());
            result.put("files", sqlFiles.stream().map(File::getName).toList());
            result.put("message", "文件扫描测试完成");
            
        } catch (Exception e) {
            log.error("文件扫描测试失败: {}", e.getMessage(), e);
            
            result.put("success", false);
            result.put("message", "文件扫描测试失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 详细调试文件扫描功能
     */
    @GetMapping("/debug-scan")
    public ResponseEntity<Map<String, Object>> debugFileScan(@RequestParam(defaultValue = "mysql") String databaseType) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("详细调试文件扫描功能，数据库类型: {}", databaseType);
            
            // 测试各种扫描策略
            Map<String, Object> debugInfo = new HashMap<>();
            
            // 测试配置
            debugInfo.put("configUpgradePath", config.getUpgradePath());
            debugInfo.put("configExecutedPath", config.getExecutedPath());
            debugInfo.put("databaseType", databaseType);
            
            // 测试各种路径
            String[] testPaths = {
                "classpath:" + config.getUpgradePath() + "/" + databaseType,
                "classpath:" + config.getUpgradePath() + "/" + databaseType + "/*.sql",
                "classpath:sql/upgrade/mysql",
                "classpath:sql/upgrade/mysql/*.sql"
            };
            
            Map<String, Boolean> pathTests = new HashMap<>();
            for (String testPath : testPaths) {
                try {
                    Resource resource = resourceLoader.getResource(testPath);
                    pathTests.put(testPath, resource.exists());
                } catch (Exception e) {
                    pathTests.put(testPath + "_error", false);
                }
            }
            debugInfo.put("pathTests", pathTests);
            
            // 测试具体文件
            String[] testFiles = {
                "sql/upgrade/" + databaseType + "/V1.0.21__test_database_upgrade.sql",
                "sql/upgrade/" + databaseType + "/V1.0.22__simple_test.sql",
                "sql/upgrade/" + databaseType + "/V1.0.24__test_pattern_resolver.sql"
            };
            
            Map<String, Boolean> fileTests = new HashMap<>();
            for (String testFile : testFiles) {
                try {
                    Resource resource = resourceLoader.getResource("classpath:" + testFile);
                    fileTests.put(testFile, resource.exists());
                } catch (Exception e) {
                    fileTests.put(testFile + "_error", false);
                }
            }
            debugInfo.put("fileTests", fileTests);
            
            // 执行实际的文件扫描
            List<File> sqlFiles = sqlFileManager.getSqlFiles(databaseType);
            
            result.put("success", true);
            result.put("databaseType", databaseType);
            result.put("fileCount", sqlFiles.size());
            result.put("files", sqlFiles.stream().map(File::getName).toList());
            result.put("debugInfo", debugInfo);
            result.put("message", "详细调试完成");
            
        } catch (Exception e) {
            log.error("详细调试失败: {}", e.getMessage(), e);
            
            result.put("success", false);
            result.put("message", "详细调试失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
    
    /**
     * 验证目录结构
     */
    @GetMapping("/validate-directory")
    public ResponseEntity<Map<String, Object>> validateDirectory() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("验证目录结构");
            boolean isValid = sqlFileManager.validateDirectoryStructure();
            
            result.put("success", true);
            result.put("directoryValid", isValid);
            result.put("message", "目录结构验证完成");
            
        } catch (Exception e) {
            log.error("目录结构验证失败: {}", e.getMessage(), e);
            
            result.put("success", false);
            result.put("message", "目录结构验证失败: " + e.getMessage());
        }
        
        return ResponseEntity.ok(result);
    }
} 